<template>
    <div class="processing-info">
        <!-- 深加工信息 -->
        <div class="info-section">
            <div class="section-header">
                <h3>深加工信息</h3>
                <el-button @click="openProcessingEdit">设置</el-button>
                <div class="section-badge">1</div>
            </div>
            <div class="info-content">
                <div class="info-row">
                    <span class="info-label">班组:</span>
                    <span class="info-value">{{ localProcessingInfo.work_Team || '生产1组' }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">负责人:</span>
                    <span class="info-value">{{ localProcessingInfo.responsible_Person || '小陈' }}</span>
                </div>
            </div>
        </div>

        <!-- 食品安全信息 -->
        <div class="info-section">
            <div class="section-header">
                <h3>食品安全信息</h3>
                <div class="section-badge">2</div>
            </div>
            <div class="image-upload-area">
                <div class="image-grid">
                    <div v-for="(image, index) in localFoodSafetyImgs" :key="index" class="image-item">
                        <img :src="image" :alt="`食品安全信息${index + 1}`" />
                        <div class="image-label">{{ getFoodSafetyLabel(index) }}</div>
                        <div class="delete-btn" @click="removeFoodSafetyImage(index)">×</div>
                    </div>
                    <div v-if="localFoodSafetyImgs.length < 5" class="upload-placeholder"
                        @click="triggerFoodSafetyUpload">
                        <i class="el-icon-plus"></i>
                    </div>
                </div>
                <input ref="foodSafetyInput" type="file" accept="image/*" style="display: none;"
                    @change="handleFoodSafetyFileChange" />
            </div>
        </div>

        <!-- 供应商信息 -->
        <div class="info-section">
            <div class="section-header">
                <h3>供应商信息</h3>
            </div>

            <!-- 原料 -->
            <div class="supplier-subsection">
                <div class="subsection-header">
                    <div class="blue-bar"></div>
                    <h4>原料</h4>
                    <el-button @click="openRawMaterialEdit">设置</el-button>
                    <div class="section-badge">3</div>
                </div>
                <div class="info-content">
                    <div class="info-row">
                        <span class="info-label">生产批次:</span>
                        <span class="info-value">{{ localProcessingInfo.batch_No || '20210718' }}</span>
                    </div>
                </div>
                <div class="materials-section">
                    <h5>相关材料</h5>
                    <div class="image-grid">
                        <div v-for="(image, index) in localRawMaterialImgs" :key="index" class="image-item">
                            <img :src="image" :alt="`原料材料${index + 1}`" />
                            <div class="image-label">{{ getRawMaterialLabel(index) }}</div>
                            <div class="delete-btn" @click="removeRawMaterialImage(index)">×</div>
                        </div>
                        <div v-if="localRawMaterialImgs.length < 5" class="upload-placeholder"
                            @click="triggerRawMaterialUpload">
                            <i class="el-icon-plus"></i>
                        </div>
                    </div>
                    <input ref="rawMaterialInput" type="file" accept="image/*" style="display: none;"
                        @change="handleRawMaterialFileChange" />
                </div>
            </div>

            <!-- 辅料 -->
            <div class="supplier-subsection">
                <div class="subsection-header">
                    <div class="blue-bar"></div>
                    <h4>辅料</h4>
                    <el-button @click="openAuxiliaryMaterialEdit">设置</el-button>
                    <div class="section-badge">4</div>
                </div>
                <div class="info-content">
                    <div class="info-row">
                        <span class="info-label">生产批次:</span>
                        <span class="info-value">{{ localProcessingInfo.batch_No || '20210718' }}</span>
                    </div>
                </div>
                <div class="materials-section">
                    <h5>相关材料</h5>
                    <div class="image-grid">
                        <div v-for="(image, index) in localAuxiliaryMaterialImgs" :key="index" class="image-item">
                            <img :src="image" :alt="`辅料材料${index + 1}`" />
                            <div class="image-label">{{ getAuxiliaryMaterialLabel(index) }}</div>
                            <div class="delete-btn" @click="removeAuxiliaryMaterialImage(index)">×</div>
                        </div>
                        <div v-if="localAuxiliaryMaterialImgs.length < 5" class="upload-placeholder"
                            @click="triggerAuxiliaryMaterialUpload">
                            <i class="el-icon-plus"></i>
                        </div>
                    </div>
                    <input ref="auxiliaryMaterialInput" type="file" accept="image/*" style="display: none;"
                        @change="handleAuxiliaryMaterialFileChange" />
                </div>
            </div>

            <!-- 添加剂 -->
            <div class="supplier-subsection">
                <div class="subsection-header">
                    <div class="blue-bar"></div>
                    <h4>添加剂</h4>
                    <el-button @click="openAdditiveEdit">设置</el-button>
                    <div class="section-badge">4</div>
                </div>
                <div class="info-content">
                    <div class="info-row">
                        <span class="info-label">生产批次:</span>
                        <span class="info-value">{{ localProcessingInfo.batch_No || '20210718' }}</span>
                    </div>
                </div>
                <div class="materials-section">
                    <h5>相关材料</h5>
                    <div class="image-grid">
                        <div v-for="(image, index) in localAdditiveImgs" :key="index" class="image-item">
                            <img :src="image" :alt="`添加剂材料${index + 1}`" />
                            <div class="image-label">{{ getAdditiveLabel(index) }}</div>
                            <div class="delete-btn" @click="removeAdditiveImage(index)">×</div>
                        </div>
                        <div v-if="localAdditiveImgs.length < 5" class="upload-placeholder"
                            @click="triggerAdditiveUpload">
                            <i class="el-icon-plus"></i>
                        </div>
                    </div>
                    <input ref="additiveInput" type="file" accept="image/*" style="display: none;"
                        @change="handleAdditiveFileChange" />
                </div>
            </div>

            <!-- 包材 -->
            <div class="supplier-subsection">
                <div class="subsection-header">
                    <div class="blue-bar"></div>
                    <h4>包材</h4>
                    <el-button @click="openPackagingMaterialEdit">设置</el-button>
                    <div class="section-badge">4</div>
                </div>
                <div class="info-content">
                    <div class="info-row">
                        <span class="info-label">生产批次:</span>
                        <span class="info-value">{{ localProcessingInfo.batch_No || '20210718' }}</span>
                    </div>
                </div>
                <div class="materials-section">
                    <h5>相关材料</h5>
                    <div class="image-grid">
                        <div v-for="(image, index) in localPackagingMaterialImgs" :key="index" class="image-item">
                            <img :src="image" :alt="`包材材料${index + 1}`" />
                            <div class="image-label">{{ getPackagingMaterialLabel(index) }}</div>
                            <div class="delete-btn" @click="removePackagingMaterialImage(index)">×</div>
                        </div>
                        <div v-if="localPackagingMaterialImgs.length < 5" class="upload-placeholder"
                            @click="triggerPackagingMaterialUpload">
                            <i class="el-icon-plus"></i>
                        </div>
                    </div>
                    <input ref="packagingMaterialInput" type="file" accept="image/*" style="display: none;"
                        @change="handlePackagingMaterialFileChange" />
                </div>
            </div>
        </div>

        <!-- 企业信息 -->
        <div class="info-section">
            <div class="section-header">
                <h3>企业信息</h3>
                <el-button @click="openEnterpriseEdit">设置</el-button>
                <div class="section-badge">5</div>
            </div>
            <div class="info-content">
                <div class="info-row">
                    <span class="info-label">公司名称:</span>
                    <span class="info-value">{{ enterpriseInfo.corporate_Name || '四川锦祥食品有限公司' }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">生产许可证号:</span>
                    <span class="info-value">{{ enterpriseInfo.production_License || 'SC213205427680' }}</span>
                </div>
            </div>
        </div>

        <!-- 企业照片 -->
        <div class="info-section">
            <div class="section-header">
                <h3>企业照片</h3>
                <div class="section-badge">6</div>
            </div>
            <div class="image-upload-area">
                <div class="image-grid">
                    <div v-for="(image, index) in localEnterprisePhotoImgs" :key="index" class="image-item">
                        <img :src="image" :alt="`企业照片${index + 1}`" />
                        <div class="delete-btn" @click="removeEnterprisePhotoImage(index)">×</div>
                    </div>
                    <div v-if="localEnterprisePhotoImgs.length < 5" class="upload-placeholder"
                        @click="triggerEnterprisePhotoUpload">
                        <i class="el-icon-plus"></i>
                    </div>
                </div>
                <input ref="enterprisePhotoInput" type="file" accept="image/*" style="display: none;"
                    @change="handleEnterprisePhotoFileChange" />
            </div>
        </div>

        <!-- 深加工信息编辑弹窗 -->
        <el-dialog v-model="processingEditVisible" title="深加工信息" width="600px">
            <el-form :model="processingForm" label-width="120px">
                <el-form-item label="班组：">
                    <el-input v-model="processingForm.work_Team" placeholder="请输入班组" />
                </el-form-item>
                <el-form-item label="负责人：">
                    <el-input v-model="processingForm.responsible_Person" placeholder="请输入负责人" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="processingEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveProcessingInfo">保存</el-button>
            </template>
        </el-dialog>

        <!-- 供应商设置弹窗 -->
        <el-dialog v-model="supplierEditVisible" title="供应商设置" width="600px">
            <el-form :model="supplierForm" label-width="120px">
                <el-form-item label="生产批次：">
                    <el-input v-model="supplierForm.batch_Number" placeholder="请输入生产批次" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="supplierEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveSupplierInfo">保存</el-button>
            </template>
        </el-dialog>

        <!-- 企业信息编辑弹窗 -->
        <el-dialog v-model="enterpriseEditVisible" title="企业信息" width="600px">
            <el-form :model="enterpriseForm" label-width="120px">
                <el-form-item label="企业名称：">
                    <el-input v-model="enterpriseForm.corporate_Name" placeholder="请输入企业名称" />
                </el-form-item>
                <el-form-item label="生产许可证号：">
                    <el-input v-model="enterpriseForm.production_License" placeholder="请输入生产许可证号" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="enterpriseEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEnterpriseInfo">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Write, Read } from '@/components/Http/axiosHepler';
import { uploadImage, deleteImage } from '@/utils/uploadHelper';
import { useCounterStore } from "@/stores/counter";

const store = useCounterStore();

// 定义props
const props = defineProps<{
    traceabilityId: number;
    processingInfo: any;
    enterpriseInfo: any;
    foodSafetyImgs: string[];
    rawMaterialImgs: string[];
    auxiliaryMaterialImgs: string[];
    additiveImgs: string[];
    packagingMaterialImgs: string[];
    enterprisePhotoImgs: string[];
}>();

// 定义emits
const emit = defineEmits<{
    'update:processingInfo': [value: any];
    'update:enterpriseInfo': [value: any];
    'update:foodSafetyImgs': [value: string[]];
    'update:rawMaterialImgs': [value: string[]];
    'update:auxiliaryMaterialImgs': [value: string[]];
    'update:additiveImgs': [value: string[]];
    'update:packagingMaterialImgs': [value: string[]];
    'update:enterprisePhotoImgs': [value: string[]];
    'food-safety-remove': [index: number, image: any];
    'raw-material-remove': [index: number, image: any];
    'auxiliary-material-remove': [index: number, image: any];
    'additive-remove': [index: number, image: any];
    'packaging-material-remove': [index: number, image: any];
    'enterprise-photo-remove': [index: number, image: any];
}>();

const processingEditVisible = ref(false);
const enterpriseEditVisible = ref(false);

// 本地图片数组，用于v-model
const localFoodSafetyImgs = ref<string[]>([]);
const localRawMaterialImgs = ref<string[]>([]);
const localAuxiliaryMaterialImgs = ref<string[]>([]);
const localAdditiveImgs = ref<string[]>([]);
const localPackagingMaterialImgs = ref<string[]>([]);
const localEnterprisePhotoImgs = ref<string[]>([]);

// 本地深加工信息数据
const localProcessingInfo = ref({
    processingId: '',
    work_Team: '',
    responsible_Person: '',
    batch_No: '',
    traceabilityId: ''
});

// 监听props变化，同步到本地数据
watch(() => props.foodSafetyImgs, (newVal) => {
    console.log('ProcessingInfo - foodSafetyImgs变化:', newVal);
    localFoodSafetyImgs.value = newVal ? [...newVal] : [];
    console.log('ProcessingInfo - localFoodSafetyImgs更新为:', localFoodSafetyImgs.value);
}, { immediate: true });

watch(() => props.rawMaterialImgs, (newVal) => {
    console.log('ProcessingInfo - rawMaterialImgs变化:', newVal);
    localRawMaterialImgs.value = newVal ? [...newVal] : [];
    console.log('ProcessingInfo - localRawMaterialImgs更新为:', localRawMaterialImgs.value);
}, { immediate: true });

watch(() => props.auxiliaryMaterialImgs, (newVal) => {
    console.log('ProcessingInfo - auxiliaryMaterialImgs变化:', newVal);
    localAuxiliaryMaterialImgs.value = newVal ? [...newVal] : [];
    console.log('ProcessingInfo - localAuxiliaryMaterialImgs更新为:', localAuxiliaryMaterialImgs.value);
}, { immediate: true });

watch(() => props.additiveImgs, (newVal) => {
    console.log('ProcessingInfo - additiveImgs变化:', newVal);
    localAdditiveImgs.value = newVal ? [...newVal] : [];
    console.log('ProcessingInfo - localAdditiveImgs更新为:', localAdditiveImgs.value);
}, { immediate: true });

watch(() => props.packagingMaterialImgs, (newVal) => {
    console.log('ProcessingInfo - packagingMaterialImgs变化:', newVal);
    localPackagingMaterialImgs.value = newVal ? [...newVal] : [];
    console.log('ProcessingInfo - localPackagingMaterialImgs更新为:', localPackagingMaterialImgs.value);
}, { immediate: true });

watch(() => props.enterprisePhotoImgs, (newVal) => {
    console.log('ProcessingInfo - enterprisePhotoImgs变化:', newVal);
    localEnterprisePhotoImgs.value = newVal ? [...newVal] : [];
    console.log('ProcessingInfo - localEnterprisePhotoImgs更新为:', localEnterprisePhotoImgs.value);
}, { immediate: true });

// 获取深加工信息
const getProcessingInfo = () => {
    Read.get('/Processing/ProcessingShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('深加工信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            const data = res.data.data;
            const processingData = Array.isArray(data) ? data[0] : data;

            if (processingData) {
                Object.assign(localProcessingInfo.value, {
                    processingId: processingData.processingId || '',
                    work_Team: processingData.work_Team || '',
                    responsible_Person: processingData.responsible_Person || '',
                    traceabilityId: processingData.traceabilityId || props.traceabilityId
                });
                console.log('更新后的本地深加工数据:', localProcessingInfo.value);
                emit('update:processingInfo', localProcessingInfo.value);
            }
        } else {
            console.log('接口返回数据为空或状态码不是200');
        }
    }).catch(err => {
        console.error('获取深加工信息失败:', err);
        ElMessage.error('获取深加工信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 获取企业信息
const getEnterpriseInfo = () => {
    console.log('开始获取企业信息，traceabilityId:', props.traceabilityId);
    if (!props.traceabilityId) {
        console.warn('traceabilityId为空，无法获取企业信息');
        return;
    }

    Read.get('/Processing/CompanyShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('企业信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            const data = res.data.data;
            const enterpriseData = Array.isArray(data) ? data[0] : data;

            if (enterpriseData) {
                const updatedInfo = {
                    corporate_Name: enterpriseData.corporate_Name || '',
                    production_License: enterpriseData.production_License || ''
                };
                console.log('更新后的企业信息:', updatedInfo);
                emit('update:enterpriseInfo', updatedInfo);
            }
        } else {
            console.log('接口返回数据为空或状态码不是200');
        }
    }).catch(err => {
        console.error('获取企业信息失败:', err);
        ElMessage.error('获取企业信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 获取供应商信息
const getSupplierInfo = () => {
    console.log('开始获取供应商信息，traceabilityId:', props.traceabilityId);
    if (!props.traceabilityId) {
        console.warn('traceabilityId为空，无法获取供应商信息');
        return;
    }

    Read.get('/Processing/SupplierShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('供应商信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            const data = res.data.data;
            const supplierData = Array.isArray(data) ? data[0] : data;

            if (supplierData) {
                // 更新本地数据中的批次号
                Object.assign(localProcessingInfo.value, {
                    batch_No: supplierData.batch_Number || '20210718',
                    traceabilityId: supplierData.traceabilityId || props.traceabilityId
                });
                console.log('更新后的供应商信息:', supplierData);
                emit('update:processingInfo', localProcessingInfo.value);
            }
        } else {
            console.log('接口返回数据为空或状态码不是200');
        }
    }).catch(err => {
        console.error('获取供应商信息失败:', err);
        ElMessage.error('获取供应商信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 更新图片数组的方法（保留用于兼容性）
const updateFoodSafetyImgs = (newImgs: string[]) => {
    localFoodSafetyImgs.value = newImgs;
    emit('update:foodSafetyImgs', newImgs);
};

const updateRawMaterialImgs = (newImgs: string[]) => {
    localRawMaterialImgs.value = newImgs;
    emit('update:rawMaterialImgs', newImgs);
};

const updateAuxiliaryMaterialImgs = (newImgs: string[]) => {
    localAuxiliaryMaterialImgs.value = newImgs;
    emit('update:auxiliaryMaterialImgs', newImgs);
};

const updateAdditiveImgs = (newImgs: string[]) => {
    localAdditiveImgs.value = newImgs;
    emit('update:additiveImgs', newImgs);
};

const updatePackagingMaterialImgs = (newImgs: string[]) => {
    localPackagingMaterialImgs.value = newImgs;
    emit('update:packagingMaterialImgs', newImgs);
};

const updateEnterprisePhotoImgs = (newImgs: string[]) => {
    localEnterprisePhotoImgs.value = newImgs;
    emit('update:enterprisePhotoImgs', newImgs);
};

// 深加工信息表单
const processingForm = reactive({
    processingId: '',
    work_Team: '',
    responsible_Person: '',
    traceabilityId: 0
});

// 企业信息表单
const enterpriseForm = reactive({
    corporate_Name: '',
    production_License: ''
});

// 打开深加工信息编辑
const openProcessingEdit = () => {
    processingForm.work_Team = localProcessingInfo.value.work_Team || '';
    processingForm.responsible_Person = localProcessingInfo.value.responsible_Person || '';
    processingForm.traceabilityId = props.traceabilityId;
    processingEditVisible.value = true;
};

// 保存深加工信息
const saveProcessingInfo = () => {
    // 验证必填字段
    const missingFields = [];

    if (!processingForm.work_Team) missingFields.push('班组');
    if (!processingForm.responsible_Person) missingFields.push('负责人');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        work_Team: processingForm.work_Team,
        responsible_Person: processingForm.responsible_Person,
        traceabilityId: props.traceabilityId
    };

    console.log('发送保存深加工信息请求:', payload);

    Write.post('/Processing/ProcessingCreate', payload).then(res => {
        console.log('保存响应:', res.data);
        if (res.data.code == 200) {
            // 更新本地数据
            Object.assign(localProcessingInfo.value, {
                processingId: res.data.data?.processingId || '',
                work_Team: processingForm.work_Team,
                responsible_Person: processingForm.responsible_Person,
                traceabilityId: props.traceabilityId
            });
            console.log('保存后更新本地数据:', localProcessingInfo.value);
            emit('update:processingInfo', localProcessingInfo.value);
            processingEditVisible.value = false;
            ElMessage.success('保存成功');
            // 重新获取数据确保同步
            getProcessingInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存深加工信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 打开企业信息编辑
const openEnterpriseEdit = () => {
    enterpriseForm.corporate_Name = props.enterpriseInfo?.corporate_Name || '';
    enterpriseForm.production_License = props.enterpriseInfo?.production_License || '';
    enterpriseEditVisible.value = true;
};

// 保存企业信息
const saveEnterpriseInfo = () => {
    // 验证必填字段
    const missingFields = [];

    if (!enterpriseForm.corporate_Name) missingFields.push('企业名称');
    if (!enterpriseForm.production_License) missingFields.push('生产许可证号');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        traceabilityId: props.traceabilityId,
        corporate_Name: enterpriseForm.corporate_Name,
        production_License: enterpriseForm.production_License
    };

    console.log('发送保存企业信息请求:', payload);

    Write.post('/Processing/CompanyCreateess', payload).then(res => {
        console.log('保存企业信息响应:', res.data);
        if (res.data.code == 200) {
            // 更新本地数据
            const updatedInfo = {
                corporate_Name: enterpriseForm.corporate_Name,
                production_License: enterpriseForm.production_License
            };
            console.log('保存后更新企业信息:', updatedInfo);
            emit('update:enterpriseInfo', updatedInfo);
            enterpriseEditVisible.value = false;
            ElMessage.success('保存成功');
            // 重新获取数据确保同步
            getEnterpriseInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存企业信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 图片上传事件处理（保留用于兼容性）
const onFoodSafetyUploadSuccess = async (image: any) => {
    console.log('食品安全信息上传成功:', image);
    if (image && image.url) {
        console.log('食品安全信息图片URL:', image.url);
        ElMessage.success('食品安全信息上传完成');
    }
};

const onFoodSafetyRemove = async (index: number, image: any) => {
    console.log('食品安全信息删除事件触发:', index, image);
    emit('food-safety-remove', index, image);
    setTimeout(() => {
        ElMessage.success('食品安全信息删除完成');
    }, 100);
};

const onRawMaterialUploadSuccess = async (image: any) => {
    console.log('原料相关材料上传成功:', image);
    if (image && image.url) {
        console.log('原料相关材料图片URL:', image.url);
        ElMessage.success('原料相关材料上传完成');
    }
};

const onRawMaterialRemove = async (index: number, image: any) => {
    console.log('原料相关材料删除事件触发:', index, image);
    emit('raw-material-remove', index, image);
    setTimeout(() => {
        ElMessage.success('原料相关材料删除完成');
    }, 100);
};

const onAuxiliaryMaterialUploadSuccess = async (image: any) => {
    console.log('辅料相关材料上传成功:', image);
    if (image && image.url) {
        console.log('辅料相关材料图片URL:', image.url);
        ElMessage.success('辅料相关材料上传完成');
    }
};

const onAuxiliaryMaterialRemove = async (index: number, image: any) => {
    console.log('辅料相关材料删除事件触发:', index, image);
    emit('auxiliary-material-remove', index, image);
    setTimeout(() => {
        ElMessage.success('辅料相关材料删除完成');
    }, 100);
};

const onAdditiveUploadSuccess = async (image: any) => {
    console.log('添加剂相关材料上传成功:', image);
    if (image && image.url) {
        console.log('添加剂相关材料图片URL:', image.url);
        ElMessage.success('添加剂相关材料上传完成');
    }
};

const onAdditiveRemove = async (index: number, image: any) => {
    console.log('添加剂相关材料删除事件触发:', index, image);
    emit('additive-remove', index, image);
    setTimeout(() => {
        ElMessage.success('添加剂相关材料删除完成');
    }, 100);
};

const onPackagingMaterialUploadSuccess = async (image: any) => {
    console.log('包材相关材料上传成功:', image);
    if (image && image.url) {
        console.log('包材相关材料图片URL:', image.url);
        ElMessage.success('包材相关材料上传完成');
    }
};

const onPackagingMaterialRemove = async (index: number, image: any) => {
    console.log('包材相关材料删除事件触发:', index, image);
    emit('packaging-material-remove', index, image);
    setTimeout(() => {
        ElMessage.success('包材相关材料删除完成');
    }, 100);
};

const onEnterprisePhotoUploadSuccess = async (image: any) => {
    console.log('企业照片上传成功:', image);
    if (image && image.url) {
        console.log('企业照片URL:', image.url);
        ElMessage.success('企业照片上传完成');
    }
};

const onEnterprisePhotoRemove = async (index: number, image: any) => {
    console.log('企业照片删除事件触发:', index, image);
    emit('enterprise-photo-remove', index, image);
    setTimeout(() => {
        ElMessage.success('企业照片删除完成');
    }, 100);
};

// 获取标签文本的函数
const getFoodSafetyLabel = (index: number) => {
    const labels = ['人员卫生情况', '抽检报告', '食品安全证书', '检验报告', '质量证明'];
    return labels[index] || `食品安全信息${index + 1}`;
};

const getRawMaterialLabel = (index: number) => {
    const labels = ['检验报告', '进厂验收记录', '供应商资质', '质量证明', '检验证书'];
    return labels[index] || `原料材料${index + 1}`;
};

const getAuxiliaryMaterialLabel = (index: number) => {
    const labels = ['检验报告', '进厂验收记录', '供应商资质', '质量证明', '检验证书'];
    return labels[index] || `辅料材料${index + 1}`;
};

const getAdditiveLabel = (index: number) => {
    const labels = ['检验报告', '进厂验收记录', '供应商资质', '质量证明', '检验证书'];
    return labels[index] || `添加剂材料${index + 1}`;
};

const getPackagingMaterialLabel = (index: number) => {
    const labels = ['检验报告', '进厂验收记录', '供应商资质', '质量证明', '检验证书'];
    return labels[index] || `包材材料${index + 1}`;
};

// 文件上传相关
const foodSafetyInput = ref<HTMLInputElement>();
const rawMaterialInput = ref<HTMLInputElement>();
const auxiliaryMaterialInput = ref<HTMLInputElement>();
const additiveInput = ref<HTMLInputElement>();
const packagingMaterialInput = ref<HTMLInputElement>();
const enterprisePhotoInput = ref<HTMLInputElement>();

// 触发文件选择
const triggerFoodSafetyUpload = () => {
    foodSafetyInput.value?.click();
};

const triggerRawMaterialUpload = () => {
    rawMaterialInput.value?.click();
};

const triggerAuxiliaryMaterialUpload = () => {
    auxiliaryMaterialInput.value?.click();
};

const triggerAdditiveUpload = () => {
    additiveInput.value?.click();
};

const triggerPackagingMaterialUpload = () => {
    packagingMaterialInput.value?.click();
};

const triggerEnterprisePhotoUpload = () => {
    enterprisePhotoInput.value?.click();
};

// 处理文件选择
const handleFoodSafetyFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        await uploadFile(target.files[0], 'Enterprise_Image', localFoodSafetyImgs, 'update:foodSafetyImgs');
    }
    target.value = '';
};

const handleRawMaterialFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        await uploadFile(target.files[0], 'Raw_Material', localRawMaterialImgs, 'update:rawMaterialImgs');
    }
    target.value = '';
};

const handleAuxiliaryMaterialFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        await uploadFile(target.files[0], 'Auxiliary_Materials', localAuxiliaryMaterialImgs, 'update:auxiliaryMaterialImgs');
    }
    target.value = '';
};

const handleAdditiveFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        await uploadFile(target.files[0], 'Additive_Materials', localAdditiveImgs, 'update:additiveImgs');
    }
    target.value = '';
};

const handlePackagingMaterialFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        await uploadFile(target.files[0], 'Packaging_Materials', localPackagingMaterialImgs, 'update:packagingMaterialImgs');
    }
    target.value = '';
};

const handleEnterprisePhotoFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        await uploadFile(target.files[0], 'Certification_Documents', localEnterprisePhotoImgs, 'update:enterprisePhotoImgs');
    }
    target.value = '';
};

// 通用上传函数
const uploadFile = async (file: File, fieldType: string, imageArray: any, emitEvent: string) => {
    try {
        const url = await uploadImage(
            file,
            (data, uploadedFile) => {
                console.log('上传成功:', data);
                imageArray.value.push(data.url || data.data?.uploadedUrls?.[0] || '');
                emit(emitEvent as any, imageArray.value);
                ElMessage.success('上传成功');
            },
            (error) => {
                console.error('上传失败:', error);
                ElMessage.error('上传失败: ' + error.message);
            },
            props.traceabilityId,
            fieldType
        );
    } catch (error: any) {
        console.error('上传异常:', error);
        ElMessage.error('上传失败: ' + error.message);
    }
};

// 删除图片函数
const removeFoodSafetyImage = async (index: number) => {
    await removeImage(index, localFoodSafetyImgs, 'Enterprise_Image', 'update:foodSafetyImgs');
};

const removeRawMaterialImage = async (index: number) => {
    await removeImage(index, localRawMaterialImgs, 'Raw_Material', 'update:rawMaterialImgs');
};

const removeAuxiliaryMaterialImage = async (index: number) => {
    await removeImage(index, localAuxiliaryMaterialImgs, 'Auxiliary_Materials', 'update:auxiliaryMaterialImgs');
};

const removeAdditiveImage = async (index: number) => {
    await removeImage(index, localAdditiveImgs, 'Additive_Materials', 'update:additiveImgs');
};

const removePackagingMaterialImage = async (index: number) => {
    await removeImage(index, localPackagingMaterialImgs, 'Packaging_Materials', 'update:packagingMaterialImgs');
};

const removeEnterprisePhotoImage = async (index: number) => {
    await removeImage(index, localEnterprisePhotoImgs, 'Certification_Documents', 'update:enterprisePhotoImgs');
};

// 通用删除函数
const removeImage = async (index: number, imageArray: any, fieldType: string, emitEvent: string) => {
    const imageUrl = imageArray.value[index];
    if (imageUrl) {
        try {
            const success = await deleteImage(props.traceabilityId, fieldType, imageUrl);
            if (success) {
                imageArray.value.splice(index, 1);
                emit(emitEvent as any, imageArray.value);
                ElMessage.success('删除成功');
            }
        } catch (error: any) {
            console.error('删除异常:', error);
            ElMessage.error('删除失败: ' + error.message);
        }
    }
};

// 供应商设置相关
const supplierEditVisible = ref(false);
const supplierForm = reactive({
    batch_Number: '',
    traceabilityId: 0
});

// 打开供应商设置
const openRawMaterialEdit = () => {
    supplierForm.batch_Number = '20210718';
    supplierForm.traceabilityId = props.traceabilityId;
    supplierEditVisible.value = true;
};

const openAuxiliaryMaterialEdit = () => {
    supplierForm.batch_Number = '20210718';
    supplierForm.traceabilityId = props.traceabilityId;
    supplierEditVisible.value = true;
};

const openAdditiveEdit = () => {
    supplierForm.batch_Number = '20210718';
    supplierForm.traceabilityId = props.traceabilityId;
    supplierEditVisible.value = true;
};

const openPackagingMaterialEdit = () => {
    supplierForm.batch_Number = '20210718';
    supplierForm.traceabilityId = props.traceabilityId;
    supplierEditVisible.value = true;
};

// 保存供应商信息
const saveSupplierInfo = () => {
    // 验证必填字段
    const missingFields = [];

    if (!supplierForm.batch_Number) missingFields.push('生产批次');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        batch_Number: supplierForm.batch_Number,
        traceabilityId: props.traceabilityId
    };

    console.log('发送保存供应商信息请求:', payload);

    Write.post('/Processing/SupplierCreate', payload).then(res => {
        console.log('保存供应商信息响应:', res.data);
        if (res.data.code == 200) {
            // 更新本地数据
            Object.assign(localProcessingInfo.value, {
                batch_No: supplierForm.batch_Number,
                traceabilityId: props.traceabilityId
            });
            console.log('保存后更新本地数据:', localProcessingInfo.value);
            emit('update:processingInfo', localProcessingInfo.value);
            supplierEditVisible.value = false;
            ElMessage.success('保存成功');
            // 重新获取数据确保同步
            getProcessingInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存供应商信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 组件挂载时获取数据
onMounted(() => {
    console.log('ProcessingInfo组件挂载，traceabilityId:', props.traceabilityId);
    console.log('ProcessingInfo组件挂载时的图片数组:');
    console.log('- foodSafetyImgs:', props.foodSafetyImgs);
    console.log('- rawMaterialImgs:', props.rawMaterialImgs);
    console.log('- auxiliaryMaterialImgs:', props.auxiliaryMaterialImgs);
    console.log('- additiveImgs:', props.additiveImgs);
    console.log('- packagingMaterialImgs:', props.packagingMaterialImgs);
    console.log('- enterprisePhotoImgs:', props.enterprisePhotoImgs);

    console.log('ProcessingInfo组件挂载时的本地图片数组:');
    console.log('- localFoodSafetyImgs:', localFoodSafetyImgs.value);
    console.log('- localRawMaterialImgs:', localRawMaterialImgs.value);
    console.log('- localAuxiliaryMaterialImgs:', localAuxiliaryMaterialImgs.value);
    console.log('- localAdditiveImgs:', localAdditiveImgs.value);
    console.log('- localPackagingMaterialImgs:', localPackagingMaterialImgs.value);
    console.log('- localEnterprisePhotoImgs:', localEnterprisePhotoImgs.value);

    if (props.traceabilityId) {
        getProcessingInfo();
        getSupplierInfo();
        getEnterpriseInfo();
    } else {
        console.warn('traceabilityId为空，无法获取深加工信息');
    }
});

// 监听traceabilityId变化
watch(() => props.traceabilityId, (newVal) => {
    if (newVal) {
        console.log('traceabilityId变化，重新获取数据:', newVal);
        getProcessingInfo();
        getSupplierInfo();
        getEnterpriseInfo();
    }
});
</script>

<style scoped>
.processing-info {
    padding: 24px;
    background: #f5f5f5;
    min-height: 100vh;
}

.info-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
    position: relative;
}

.section-header h3 {
    margin: 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
}

.section-badge {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #909399;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
}

.info-content {
    margin-bottom: 16px;
}

.info-row {
    display: flex;
    margin-bottom: 8px;
    align-items: center;
}

.info-label {
    color: #606266;
    font-size: 14px;
    min-width: 80px;
    margin-right: 8px;
}

.info-value {
    color: #303133;
    font-size: 14px;
    font-weight: 500;
}

.image-upload-area {
    margin-top: 16px;
}

.image-grid {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

.image-item {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #e4e7ed;
}

.image-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-label {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.7);
    color: #fff;
    font-size: 12px;
    padding: 4px 8px;
    text-align: center;
}

.delete-btn {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 20px;
    height: 20px;
    background: rgba(255, 0, 0, 0.8);
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
}

.upload-placeholder {
    width: 120px;
    height: 120px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background: #fafafa;
    transition: all 0.3s;
}

.upload-placeholder:hover {
    border-color: #409eff;
    background: #f0f9ff;
}

.upload-placeholder i {
    font-size: 24px;
    color: #d9d9d9;
}

.upload-placeholder:hover i {
    color: #409eff;
}

.supplier-subsection {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fafafa;
}

.subsection-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    gap: 8px;
}

.blue-bar {
    width: 4px;
    height: 20px;
    background: #409eff;
    border-radius: 2px;
}

.subsection-header h4 {
    margin: 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
    flex: 1;
}

.materials-section {
    margin-top: 12px;
}

.materials-section h5 {
    margin: 0 0 8px 0;
    color: #606266;
    font-size: 13px;
    font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .processing-info {
        padding: 16px;
    }

    .info-section {
        padding: 16px;
    }

    .image-grid {
        gap: 8px;
    }

    .image-item,
    .upload-placeholder {
        width: 100px;
        height: 100px;
    }
}
</style>